package org.example.judge_pojo;

import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

@Data
@TableName("tb_auth")
public class Auth implements Serializable {
    /**
     * 权限表主键
     */
    private java.lang.String id;

    /**
     * 权限名称
     */
    private java.lang.String name;

    /**
     * 权限编码
     */
    private java.lang.String code;

    /**
     * 状态0可用1不可用
     */
    private java.lang.Integer status;

    /**
     * 创建时间
     */
    private Date createTime;

    /**
     * 修改时间
     */
    private Date updateTime;
    //普通管理
    public static final String ADMINISTRATOR = "1-Administrator";

    //用户
    public static final String CLIENT = "2-Client";

    //root
    public static final String ROOT = "0-Root";
    //全部
    public static final String[] AUTHS = {CLIENT,ADMINISTRATOR, ROOT};
    /**
     * 判断用户是否为管理员
     * @param user
     * @return
     */
    public static boolean isAdmin(User user){
        if(user==null)return false;
        else{
            List<Auth> auths = user.getAuths();
            if(auths==null)return false;
            for (Auth auth : auths) {
                if(auth.getCode().equalsIgnoreCase(Auth.ADMINISTRATOR)||auth.getCode().equalsIgnoreCase(Auth.ROOT)){
                    return true;
                }
            }
        }
        return false;
    }
    /**
     * 判断用户是否有权限
     * @param user
     * @return
     */
    public static boolean isAdmin(User user,String... authCode){
        if(user==null)return false;
        else{
            List<Auth> auths = user.getAuths();
            if(auths==null)return false;
            for (Auth auth : auths) {
                if(auth.getCode().equalsIgnoreCase(Auth.ADMINISTRATOR)||auth.getCode().equalsIgnoreCase(Auth.ROOT)){
                    return true;
                }
                for (String s : authCode) {
                    if(auth.getCode().equalsIgnoreCase(s))return true;
                }

            }
        }
        return false;
    }
    /**
     * 是否为保留权限
     * @param auth
     * @return
     */
    public static boolean isKeep(String auth){
        return ADMINISTRATOR.equals(auth)||CLIENT.equals(auth)|| ROOT.equals(auth);
    }

    /**
     * 是否满足访问权限
     * @param userAuth
     * @param apiAuth
     * @return
     */
    public  static  boolean isAuth(String userAuth,String apiAuth){
        if(userAuth.equalsIgnoreCase(apiAuth))return true;
        if(isKeep(userAuth)&&isKeep(apiAuth)){  //是否都为保留权限
            return userAuth.charAt(0)<=apiAuth.charAt(0);  //权限等级比较
        }
        return false;

    }
}
